﻿using System;
using System.Data;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using KPIS.GERP.OMVC.Models;
using KPIS.GERP.OMVC.Classes;
using KPIS.GERP.OMVC.SysApprovalService;
using KPIS.GERP.Models;
using KPIS.GERP.Models.HRM;
using System.Collections.Generic;
using KPIS.GERP.Models.SYS;
using System.Data.Entity;

namespace KPIS.GERP.OMVC.Controllers
{
    public class SalaryPromoteController : Controller
    {
        GERPContext db = new GERPContext(true);
        SsMng ssMng = new SsMng();
        //Employee employeeDal = new Employee();
        //SalaryPromoteDal salaryPromoteDal = new SalaryPromoteDal();

        public ActionResult Index()
        {
            var sps = db.SalaryPromotes.OrderByDescending(o => o.SpId).ToList();
            // salaryPromoteDal.Select().OrderByDescending(o => o.sp_seq).ToList();
            return View(sps);
        }

        public ActionResult ViewDetails(int RefSeq)
        {
            var sp = db.SalaryPromotes.Find(RefSeq);// salaryPromoteDal.Select(new salary_promote { sp_seq = RefSeq }).First();
            //approval_task approvalTask = null;
            //approval_task[] allApprovalTask = null;
            ViewBag.Details = db.SalaryPromoteDetails.Where(o => o.SpId == RefSeq).OrderBy(o=>o.Position.PosNo).ToList();
            if (sp != null)
            {
                //using (var service = new ApprovalServiceWcfIisRef.AbsenceApprovalWCFClient())
                //{
                //    //allApprovalTask = service.GetTasks();
                //}
            }

            //if (allApprovalTask != null)
            //{
            //    approvalTask = allApprovalTask.FirstOrDefault(o => o.Reference.ref_seq == sp.sp_seq && o.Reference.rule_approve_group_seq == 1001);
            //}

            ViewBag.sp = sp;

            return View();// ;approvalTask);
        }

        public ActionResult Create()
        {
            var positions = db.Positions;//employeeDal.GetHrmMpPositions(null, null, null, null, null, null, null, null, false, false, false, false, false, false);
            
            ViewBag.Positions = positions
                .Select(c => new SelectListItem
                {
                    Value = c.PosId.ToString(),
                    Text = c.PosNo + " - " + c.Name
                });

            ViewBag.EmployeesActive = db.Employees;// employeeDal.GetHrmPsEmployeeLite();

            return View();
        }

        [HttpPost]
        public ActionResult Create(SalaryPromote model, FormCollection formCollection)
        {
            string resultMessage = "ยังไม่ทำอะไร";
            model.CreatedBy = ssMng.EmpSeqI;

            List<SalaryPromoteDetail> datadetail = new List<SalaryPromoteDetail>();
            var employees = db.Employees.Where(o=>o.MasEmployeeStatus != null && o.MasEmployeeStatus.Active == "1"); // employeeDal.GetHrmPsEmployeeLite();
            var common = new Classes.Common();
            foreach (var employee in employees)
            {
                if (formCollection["EmpChbSalary_" + employee.EmpId].StartsWith("true"))
                {
                    datadetail.Add(new SalaryPromoteDetail
                        {
                            EmpId = employee.EmpId,
                            OldSalary = common.MakeZeroDecimal(formCollection["EmpOldSalary_" + employee.EmpId]),
                            NewSalary = common.MakeZeroDecimal(formCollection["EmpTxtSalary_" + employee.EmpId]),
                            PosId = employee.PosId.Value,
                            SpId = model.SpId
                        });
                }
            }
            //model.Details = datadetail;
            foreach (var key in formCollection.AllKeys)
            {

                resultMessage += key + " = " + formCollection[key] + "\r\n";
                // etc.
            }
            resultMessage += "----\r\n";
            foreach (var key in formCollection.Keys)
            {
                resultMessage += key + " = " + formCollection[key.ToString()] + "\r\n";
                // etc.
            }
            db.SalaryPromotes.Add(model); // SalaryPromoteDal.Insert(model);
            ViewBag.Message = resultMessage;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Edit(int sp_seq)
        {
            var sp = new GERPContext(true).SalaryPromotes.Find(sp_seq);//.Select(new SalaryPromote { SpId = sp_seq }).First();
            return View(sp);
        }

        [HttpPost]
        public ActionResult Edit(SalaryPromote model)
        {
            try
            {
                db.Entry(model).State = EntityState.Modified;//salaryPromoteDal.Update(model);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int sp_seq)
        {
            var sp = new GERPContext(true).SalaryPromotes.Find(sp_seq);// salaryPromoteDal.Select(new salary_promote { sp_seq = sp_seq }).First();
            return View(sp);
        }

        [HttpPost]
        public ActionResult Delete(int sp_seq, FormCollection collection)
        {
            try
            {
                db.SalaryPromotes.Find(sp_seq).RecordStatus = "D"; //salaryPromoteDal.Delete(sp_seq, ssMng.EmpSeqI);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Confirm(int? EmpId, int RefSeq, int RefTypeSeq, string status, string requestTitle)
        {
            if (String.IsNullOrWhiteSpace(EmpId.ToString()) || String.IsNullOrWhiteSpace(RefSeq.ToString())
                || String.IsNullOrWhiteSpace(status))
            {
                ViewBag.Message = "รูปแบบข้อมูลไม่ถูกต้อง";
                return RedirectToAction("Create", "SalaryPromote");
            }
            else
            {
                SendApproval app = new SendApproval();
                app.Title = requestTitle;
                app.AbsenceSeq = RefSeq;
                app.EmpSeq = (int)EmpId;
                app.Status = status;

                try
                {
                    //using (var serviceClient = new ApprovalServiceIisRef.ServiceClient())
                    //{
                    //    string outMessage;
                    //    serviceClient.CreateAbsenceTask(app.Title, app.EmpSeq, app.AbsenceSeq,
                    //        app.Status, RefTypeSeq, "A", ssMng.EmpSeqI, out outMessage);
                    //    ViewBag.Message = outMessage;
                    //}
                    using(var service = new SysApprovalServiceClient())
                    {
                        var result = service.CreateTask(new KPIS.GERP.Models.SYS.ViewModel.CreateTaskVM
                            {
                                Title = app.Title,
                                ApplyToEmpId = app.EmpSeq,
                                RefId = app.AbsenceSeq,
                                AppPrcId = /*(ApproveProcessEnum) */RefTypeSeq,
                                ConfirmAs = app.Status,
                                ApproveAs = "A",
                                CreateByEmpId = app.EmpSeq
                            });
                    }
                }
                catch (HttpException ex)
                {
                    return HttpNotFound("อินเตอร์เน็ตไม่สามารถใช้งานได้");
                }
                catch (Exception ex)
                {
                    return HttpNotFound("ไม่สามารถใช้งานได้เนื่องจาก:" + ex.Message);
                }
            }
            //if (status == KPIS.GERP.SERVICE.WorkflowService.Class.Common.ProcessStatus)
            //    return RedirectToAction("Index", "ApprovalTask");
            //else
            return RedirectToAction("ViewDetails", "SalaryPromote", new { RefSeq });
        }
    }
}
